package com.keyboardr.gamerater;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.widget.ListView;

public class GamesFragment extends ListFragment {

	private Player filter;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		if (bundle != null
				&& bundle.getString("filter") != null
				&& ((RaterActivity) getActivity()).getSelectedGroup() != null
				&& bundle.getInt("lastGroupSize", -1) == ((RaterActivity) getActivity())
						.getSelectedGroup().getPlayers().size()) {
			try {
				filter = new Player(new JSONObject(bundle.getString("filter")));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			bundle.getInt("lastGroupSize", -1);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		setListAdapter(new GameAdapter((RaterActivity) getActivity(), filter));
		getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
		if (filter != null) {
			bundle.putString("filter", filter.toJSON().toString());
			bundle.putInt("lastGroupSize", ((RaterActivity) getActivity())
					.getSelectedGroup().getPlayers().size());
		}
	}

	public void setFilter(Player filter) {
		this.filter = filter;
		((GameAdapter) getListAdapter()).setGameFilter(filter);
	}
}
